<template>
    <div class="carousel-admin">
        <span>轮播图管理</span>
        <el-card>
            <div slot="header" class="clearfix">
                <el-button type="primary" @click="handleAdd">
                    添加轮播图
                </el-button>
            </div>

            <el-table :data="carousels" border :header-cell-style="{ background: '#F5F6FA', color: '#000' }"
                style="width: 100%">
                <el-table-column prop="carouselId" label="ID" width="80"></el-table-column>
                <el-table-column label="图片" width="260">
                    <template slot-scope="scope">
                        <el-image v-if="scope.row.imageUrl" style="width: 240px; height: 120px;"
                            :src="$getImgUrl(scope.row.imageUrl)" fit="cover" />
                        <span v-else>暂无图片</span>
                    </template>
                </el-table-column>
                <el-table-column prop="imageUrl" label="图片地址"></el-table-column>
                <el-table-column prop="sort" label="排序" width="100"></el-table-column>
                <el-table-column label="操作" width="220">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="footer" v-if="page.total > 0">
                <el-pagination background :current-page="page.pageNum" :page-size="page.pageSize"
                    layout="total, prev, pager, next" :total="page.total">
                </el-pagination>
            </div>
        </el-card>

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
            <el-form :model="form" :rules="rules" ref="form">
                <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
                    :show-file-list="false" :before-upload="beforeAvatarUpload" :auto-upload="false"
                    :on-change="handleChange">
                    <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.sort" :min="0"></el-input-number>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getCarousels, addCarousel, removeCarousel, updateCarousel } from '@/apis/carousel'
import { uploadFile } from '@/apis/files'

export default {
    name: 'CarouselAdmin',
    data() {
        return {
            carousels: [],
            page: {
                pageNum: 1,
                pageSize: 5,
                total: 0
            },
            dialogVisible: false,
            dialogTitle: '添加轮播图',
            form: {
                carouselId: null,
                imageUrl: '',
                sort: 0
            },
            selectedFile: null,
            rules: {
                imageUrl: [
                    { required: true, message: '请输入图片地址', trigger: 'blur' }
                ],
                sort: [
                    { type: 'number', required: true, message: '请输入排序值', trigger: 'change' }
                ]
            }
        }
    },
    created() {
        this.getCarouselList()
    },
    methods: {

        //文件上传监听
        handleChange(file) {
            this.selectedFile = file.raw;
            this.form.imageUrl = URL.createObjectURL(file.raw);
        },

        //文件上传格式
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },

        //获取轮播图列表
        async getCarouselList() {
            const res = await getCarousels()
            if (res && res.data) {
                this.carousels = res.data.records || []
                this.page.total = res.data.total || this.carousels.length
            }
        },

        //添加轮播图
        handleAdd() {
            this.dialogTitle = '添加轮播图'
            this.form = {
                carouselId: null,
                imageUrl: '',
                sort: 0
            }
            this.dialogVisible = true
        },

        //编辑轮播图
        handleEdit(row) {
            this.dialogTitle = '编辑轮播图'
            this.form = {
                carouselId: row.carouselId,
                imageUrl: this.$getImgUrl(row.imageUrl),
                sort: row.sort
            }
            this.dialogVisible = true
        },

        //删除轮播图
        handleDelete(row) {
            this.$confirm('确认删除该轮播图吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeCarousel(row.carouselId).then(() => {
                    this.getCarouselList()
                })
            })
        },

        //提交表单
        submitForm() {
            this.$refs.form.validate(valid => {
                if (!valid) return

                const doRequest = () => {
                    const payload = {
                        imageUrl: this.form.imageUrl,
                        sort: this.form.sort
                    }

                    const request = this.form.carouselId
                        ? updateCarousel(this.form.carouselId, payload)
                        : addCarousel(payload)

                    request.then(() => {
                        this.dialogVisible = false
                        this.selectedFile = null
                        this.getCarouselList()
                    })
                }

                // 如果选择了新文件，先上传文件，拿到 data 作为真正的图片路径
                if (this.selectedFile) {
                    const path = 'banner'
                    uploadFile(this.selectedFile, path).then(res => {
                        if (res && res.message) {
                            this.form.imageUrl = res.data
                            doRequest()
                        } else {
                            this.$message.error('图片上传失败，未返回路径')
                        }
                    }).catch(() => {
                        this.$message.error('图片上传失败')
                    })
                } else {
                    // 未重新选择文件时，要求已有有效的 imageUrl
                    if (!this.form.imageUrl) {
                        this.$message.error('请先上传图片')
                        return
                    }
                    doRequest()
                }
            })
        }
    }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.carousel-admin {
    padding: 20px;
}
</style>
